const productModel = require('../models/productModel');
const { sendSuccess, sendError } = require('../utils/response');

module.exports = {
  // 获取所有商品
  async getAllProducts(req, res) {
    try {
      const { category_id, is_featured, keyword, page = 1, limit = 10 } = req.query;
      const productItems = await productModel.getAllProducts({ category_id, is_featured, keyword, page, limit });
      sendSuccess(res, productItems);
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 获取商品详情
  async getProductById(req, res) {
    try {
      const { id } = req.params;

      const product = await productModel.getProductById(id);
      sendSuccess(res, product);
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 商家添加商品
  async createProduct(req, res) {
    try {
      const { id, role } = req.user;
      const { name, description, price, stock, category_id, is_featured } = req.body;
      const images = req.files?.map(file => `/public/uploads/${file.filename}`).join(',') || '';
      const insertId = await productModel.createProduct(id, { name, description, price, stock, category_id, is_featured, images });
      sendSuccess(res, insertId, '商品添加成功', 201);
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 商家更新商品
  async updateProduct(req, res) {
    try {
      const { id, role } = req.user;
      const productId = req.params.id;

      if (role !== 'merchant') {
        return sendError(res, '只有商家可以更新商品', 403);
      }

      // 检查商品是否属于该商家


      const [products] = await productModel.getProductsByMerchantId(id, productId);


      if (products.length === 0) {
        return sendError(res, '商品不存在或无权修改', 404);
      }

      const { name, description, price, stock, category_id, is_featured, status } = req.body;
      let images = products.images;

      if (req.files && req.files.length > 0) {
        images = req.files.map(file => `/public/uploads/${file.filename}`).join(',');
      }

      

      const result = await productModel.updateProduct(id, productId, { name, description, price, stock, category_id, is_featured, status, images });
      sendSuccess(res, result, '商品更新成功');
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 商家删除商品
  async deleteProduct(req, res) {
    try {
      const { id, role } = req.user;
      let productId = req.params.id;

      if (role !== 'merchant') {
        return sendError(res, '只有商家可以删除商品', 403);
      }

      // 检查商品是否属于该商家
      let reuslt = await productModel.deleteProduct(id, productId);
      sendSuccess(res, null, '商品删除成功');
    } catch (err) {
      sendError(res, err.message);
    }
  },
  // 获取推荐商品
  async getFeaturedProducts(req, res) {
    try {
      const { limit = 10 } = req.query;
      const products = await productModel.getFeaturedProducts(parseInt(limit));
      sendSuccess(res, products);
    } catch (err) {
      sendError(res, err.message);
    }
  }
};